<?php
/**
 * The model file of company module of ZenTaoPMS.
 *
 * @copyright   Copyright 2009-2015 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      Chunsheng Wang <chunsheng@cnezsoft.com>
 * @package     company
 * @version     $Id: model.php 5086 2013-07-10 02:25:22Z wyd621@gmail.com $
 * @link        http://www.zentao.net
 */
?>
<?php

class approvalModel extends model
{

    /**
     * Set menu.
     *
     * @param  int    $dept
     * @access public
     * @return void
     */
    public function setMenu($dept = 0)
    {
        common::setMenuVars($this->lang->approval->menu, 'code', array($this->app->approval->code));
        common::setMenuVars($this->lang->approval->menu, 'view', array($dept));
        common::setMenuVars($this->lang->approval->menu, 'create', array($dept));
    }

    public function getById($id)
    {
        return $this->dao->findById((int)$id)->from(TABLE_APPROVAL)->fetch();
    }


    /**
     * Get the first approval.
     *
     * @access public
     * @return void
     */
    public function getFirst() {
        return $this->dao->select('*')->from(TABLE_APPROVAL)->Where('deleted')->eq(0)->orderBy('id')->limit(1)->fetch();
    }

    public function getApprovalByCode($code = 0) {
        $approval = $this->dao->select('*')->from(TABLE_APPROVAL)
            ->Where('deleted')->eq(0)
            ->andWhere('code')->eq($code)
            ->fetch();
        return $approval;
    }
    public function getApprovals($code = 0) {
        $approval = $this->dao->select('*')->from(TABLE_APPROVAL)
            ->Where('deleted')->eq(0)
            ->andWhere('code')->eq($code)
            ->fetchAll('id');
        return $approval;
    }

    public function update()
    {
        $depts = $this->loadModel('dept')->getOptionMenu();
        $approval = fixer::input('post')->get();
        if (empty($approval->code)) {
            $time = $approval->approvalDate;
            $approval->code = strftime("%Y%m%d",strtotime(date($time))) . time();
            $this->dao->insert(TABLE_APPROVAL)
                ->data($approval)
                ->autoCheck()
                ->batchCheck($this->config->approval->edit->requiredFields, 'notempty')
                ->check('project', 'unique', "code != $approval->code and deleted='0'")
                ->exec();

            $itemValue = $this->getApprovalByCode($approval->code);
            $project = $this->dao->select('*')->from(TABLE_PROJECT)->where('name')->eq($itemValue->project)->fetch();
            $projectID = $project->id;
            if (empty($projectID)) {
                $this->dao->insert(TABLE_PROJECT)
                    ->set('name')->eq($approval->project)
                    ->set('PM')->eq($approval->leader)
                    ->set('begin')->eq($approval->beginDate)
                    ->set('end')->eq($approval->endDate)
                    ->set('days')->eq($this->time2Units(strtotime($approval->endDate) - strtotime($approval->beginDate)))
                    ->set('team')->eq(mb_substr(($depts[$approval->dept]),1,mb_strlen(($depts[$approval->dept])),'utf-8'))
                    ->set('approval')->eq($itemValue->id)
                    ->set('acl')->eq('private')
                    ->check('name', 'unique', "deleted='0'")
                    ->exec();
                $project = $this->dao->select('*')->from(TABLE_PROJECT)->where('name')->eq($approval->project)->fetch();
                if(!empty($approval->leader) and !empty($approval->dept)) {
//                    $users = $this->dao->select('*')->from(TABLE_USER)->where('dept')->eq($approval->dept)->fetchAll();
//                    foreach ($users as $id => $user) {
//                        $member = new stdclass();
//                        $member->root    = (int)$project->id;
//                        $member->account = $user->account;
//                        $member->join    = helper::today();
//                        $member->role    = $this->lang->user->roleList[$user->role];
//                        $member->days    = $project->days;
//                        $member->type    = 'project';
//                        $member->hours   = $this->config->project->defaultWorkhours;
//                        $this->dao->replace(TABLE_TEAM)->data($member)->exec();
//                    }
                    $member = new stdclass();
                    $member->root    = (int)$project->id;
                    $member->account = $approval->leader;
                    $member->join    = helper::today();
                    $member->role    = $this->lang->user->roleList['td'];
                    $member->days    = $project->days;
                    $member->type    = 'project';
                    $member->hours   = $this->config->project->defaultWorkhours;
                    $this->dao->replace(TABLE_TEAM)->data($member)->exec();
                    $this->loadModel('user')->updateUserView($project->id, 'project');
                }
            } else {
                $this->dao->update(TABLE_PROJECT)
                    ->set('`name`')->eq($approval->project)
                    ->set('`PM`')->eq($approval->leader)
                    ->set('`begin`')->eq($approval->beginDate)
                    ->set('`end`')->eq($approval->endDate)
                    ->set('`days`')->eq($this->time2Units(strtotime($approval->endDate) - strtotime($approval->beginDate)))
                    ->set('`team`')->eq(mb_substr(($depts[$approval->dept]),1,mb_strlen(($depts[$approval->dept])),'utf-8'))
                    ->set('approval')->eq($approval->id)
                    ->check('name', 'unique', "id !=$project->id and deleted='0'")
                    ->where('id')->eq($project->id)
                    ->exec();
            }
        } else {
            $approval->marketDemand = $this->enterCoverBr($approval->marketDemand);
            $approval->content = $this->enterCoverBr($approval->content);
            $approval->indicators = $this->enterCoverBr($approval->indicators);
            $approval->difficulties = $this->enterCoverBr($approval->difficulties);
            $approval->opponent = $this->enterCoverBr($approval->opponent);

            $approval->strategic = $this->enterCoverBr($approval->strategic);
            $approval->feasibility = $this->enterCoverBr($approval->feasibility);
            $approval->market = $this->enterCoverBr($approval->market);
            $approval->strategy = $this->enterCoverBr($approval->strategy);
            $approval->productionConditions = $this->enterCoverBr($approval->productionConditions);
            $approval->resourceAllocation = $this->enterCoverBr($approval->resourceAllocation);
            $approval->competitiveAdvantage = $this->enterCoverBr($approval->competitiveAdvantage);

            $this->dao->update(TABLE_APPROVAL)
                ->data($approval)
                ->autoCheck()
                ->batchCheck($this->config->approval->edit->requiredFields, 'notempty')
                ->check('name', 'unique', "deleted='0'")
                ->where('code')->eq($approval->code)
                ->exec();

            $project = $this->dao->select('*')->from(TABLE_PROJECT)->where('name')->eq($approval->project)->fetch();
            if (empty($project)) {
                $this->dao->insert(TABLE_PROJECT)
                    ->set('name')->eq($approval->project)
                    ->set('PM')->eq($approval->leader)
                    ->set('begin')->eq($approval->beginDate)
                    ->set('end')->eq($approval->endDate)
                    ->set('days')->eq($this->time2Units(strtotime($approval->endDate) - strtotime($approval->beginDate)))
                    ->set('team')->eq(mb_substr(($depts[$approval->dept]),1,mb_strlen(($depts[$approval->dept])),'utf-8'))
                    ->set('approval')->eq($approval->id)
                    ->set('acl')->eq('private')
                    ->check('name', 'unique', "deleted='0'")
                    ->exec();

                $project = $this->dao->select('*')->from(TABLE_PROJECT)->where('name')->eq($approval->project)->fetch();
                if(!empty($approval->leader) and !empty($approval->dept)) {
//                    $users = $this->dao->select('*')->from(TABLE_USER)->where('dept')->eq($approval->dept)->fetchAll();
//                    foreach ($users as $id => $user) {
//                        $member = new stdclass();
//                        $member->root    = (int)$project->id;
//                        $member->account = $user->account;
//                        $member->join    = helper::today();
//                        $member->role    = $this->lang->user->roleList[$user->role];
//                        $member->days    = $project->days;
//                        $member->type    = 'project';
//                        $member->hours   = $this->config->project->defaultWorkhours;
//                        $this->dao->replace(TABLE_TEAM)->data($member)->exec();
//                    }
                    $member = new stdclass();
                    $member->root    = (int)$project->id;
                    $member->account = $approval->leader;
                    $member->join    = helper::today();
                    $member->role    = $this->lang->user->roleList['td'];
                    $member->days    = $project->days;
                    $member->type    = 'project';
                    $member->hours   = $this->config->project->defaultWorkhours;
                    $this->dao->replace(TABLE_TEAM)->data($member)->exec();
                    $this->loadModel('user')->updateUserView($project->id, 'project');
                }
            } else {
                $this->dao->update(TABLE_PROJECT)
                    ->set('`name`')->eq($approval->project)
                    ->set('`PM`')->eq($approval->leader)
                    ->set('`begin`')->eq($approval->beginDate)
                    ->set('`end`')->eq($approval->endDate)
                    ->set('`days`')->eq($this->time2Units(strtotime($approval->endDate) - strtotime($approval->beginDate)))
                    ->set('`team`')->eq(mb_substr(($depts[$approval->dept]),1,mb_strlen(($depts[$approval->dept])),'utf-8'))
                    ->set('approval')->eq($approval->id)
                    ->check('name', 'unique', "id !=$project->id and deleted='0'")
                    ->where('id')->eq($project->id)
                    ->exec();
            }
        }
    }

    public function delete($code = 0) {
        $this->dao->update(TABLE_APPROVAL)
            ->set('deleted')->eq(1)
            ->where('code')->eq($code)
            ->exec();
    }

    public function enterCoverBr ($str) {
        return preg_replace('/\n/','&lt;br/&gt;', $str);
    }

    public function brCoverEnter ($str) {
        return str_replace('&lt;br/&gt;','<w:br/>', $str);
    }

    /**
     * 时间差计算
     *
     * @param Timestamp $time
     * @return String Time Elapsed
     * @author Shelley Shyan
     * @copyright http://phparch.cn (Professional PHP Architecture)
     */
    function time2Units ($time){
        $year   = floor($time / 60 / 60 / 24 / 365);
//        $time  -= $year * 60 * 60 * 24 * 365;
        $month  = floor($time / 60 / 60 / 24 / 30);
//        $time  -= $month * 60 * 60 * 24 * 30;
        $week   = floor($time / 60 / 60 / 24 / 7);
//        $time  -= $week * 60 * 60 * 24 * 7;
        $day    = floor($time / 60 / 60 / 24);
//        $time  -= $day * 60 * 60 * 24;
        $hour   = floor($time / 60 / 60);
//        $time  -= $hour * 60 * 60;
        $minute = floor($time / 60);
//        $time  -= $minute * 60;
        $second = $time;
        $elapse = '';

        return $day;
        $unitArr = array('年'  =>'year', '个月'=>'month',  '周'=>'week', '天'=>'day','小时'=>'hour', '分钟'=>'minute', '秒'=>'second');

        foreach ( $unitArr as $cn => $u ) {
//            $$u解释 :$u=year $$u=$year
            if ( $$u > 0 ){
                $elapse = $$u . $cn;
                break;
            }
        }

        return $elapse;
    }

    public function cleanBr($str) {
        return str_replace('&lt;br/&gt;','', $str);
    }

    public function covertUnit($money) {
        $length = strlen($money);
        if ($length > 4 && $length%4 > 0) {
            return substr($money,0,$length%4) . ' 万元';
        } else {
            return $money . ' 元';
        }
    }
}
